import util from './tools'
import sha256 from './crypto-js/sha256';
let isDev = Config.env === 'dev'
let Secret = isDev?'8kacdno8mootif084df5708z349raid5':'8kacdno8mootif084df5708z349raid5';
let Cookies = isDev? "4zl0ol101l1":"4zl0ol101l1";

const headers = {
  // 设备号
  'X-CLIENT-ID': function () {
    return util.getClientID()
  },
   // 客户端类型区分 [h5 mini userAndroidApp userIosApp shopAndroidApp shopIosApp]
  'X-CLIENT-APPID': function () {
    return 'h5'
  },

  'X-CLIENT-TICKET': function () {
    return ''
  },
   // APP版本号
  'X-CLIENT-VERSION': function() {
    return '1.0.0'
  },
    // 手机系统平台
  'X-CLIENT-PLATFORM': function () {
    const UA = navigator.userAgent
    let systemInfo = 'unknow';
      if( /(iPhone|iPad|iPod|IOS)/i.test(UA)){
          systemInfo = 'ios'
      }else if(/android/i.test(UA)){
          systemInfo = 'android'
      }else if(/microMessenger/i.test(UA)){
          systemInfo = 'Wechat'
      }
    return systemInfo
  },
    // 13位时间戳
  'X-CLIENT-TIME': function () {
    const now = new Date()
    return now.getTime()
  },

  'X-CLIENT-PAGE': function () {
      const pages = window.location.href
      return pages
  },
  // 32位随机数
  'X-CLIENT-NONCE': function() {
    return util.newUUID(true)
  }
}

/**
 * map升序排序 拼接secret
 * @param {*} params
 * @returns
 */
function sortMapJoin(params = {}) {
    // 对象的value值做升序
    let arr = Object.values(params).sort();
    let keyArr = Object.keys(params)
    let tempArr = arr.map(item=>{
        let currentKey = ''
        keyArr.forEach(key=>{
            if(params[key] == item){
                currentKey = key;
                return
            }
        })
        // 数组里面拼接 key+val
        return currentKey + item
    })
    tempArr.push(Secret)
    let destStr = tempArr.join("&");
    return String(destStr)
}

// 签名的算法
const getSign = function (header) {
    let parms = {};
    parms['nonce'] = String(header['X-CLIENT-NONCE']);
    parms['timestamps'] = String(header['X-CLIENT-TIME']).split("").reverse().join("");
    parms['cookie'] = Cookies;
    let sourceUrl = sortMapJoin(parms);
    return sha256(sourceUrl).toString()
}

export default {
    getHeaders () {
        let header = {}
        Object.keys(headers).forEach(key => {
            header[key] = headers[key].apply(this)
        })
        header['X-CLIENT-SIGN'] = getSign(header);
        return header
    }
}

